package com.irdstudio.apicenter.console.controller.monitor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.irdstudio.apicenter.console.controller.MacmsBaseAction;
import com.irdstudio.apicenter.console.dm.AppDeviceRegister;
import com.irdstudio.apicenter.console.dm.AppTradeLog;
import com.irdstudio.apicenter.console.service.authenticate.AppDeviceRegisterService;
import com.irdstudio.apicenter.frame.core.jdbc.container.PageInfo;

@Controller
@RequestMapping(value = "/monitor")
public class MonitorFrameAction extends MacmsBaseAction {
	
	@Autowired
	private AppDeviceRegisterService appDeviceRegisterService;
	//@Autowired
	//private AppTradeLogService appTradeLogService;

	private static final long serialVersionUID = 4989311084866378322L;

	/**
	 * 应用监控首页
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "main")
	public ModelAndView main(HttpServletRequest request) throws Exception {
		String appid = request.getParameter("appid");
		String appName = java.net.URLDecoder.decode(request
				.getParameter("appName"), "UTF-8");
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("appid", appid);
		modelAndView.addObject("appName", appName);
		modelAndView.setViewName("monitor/index");
		return modelAndView;
	}
	
	@RequestMapping(value = "j2eeMonitor")
	public ModelAndView j2eeMonitor(HttpServletRequest request) throws Exception {
		String appid = request.getParameter("appid");
		String appName = java.net.URLDecoder.decode(request
				.getParameter("appName"), "UTF-8");
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("appid", appid);
		modelAndView.addObject("appName", appName);
		modelAndView.setViewName("monitor/j2eeMonitorIndex");
		return modelAndView;
	}	

	/**
	 * 监控(综合信息)
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "monitor")
	public String monitor(HttpServletRequest request) throws Exception {

		// 取得传入应用标识
		String appId = request.getParameter("appid");
		if (StringUtils.isEmpty(appId)) {
			throw new Exception("必须传入应用标识(appid)参数!");
		}

		// 查询应用基本数据并放入到上下文中
		String sql = "select * from app_base_info where app_id=?";
		PageInfo abiPageInfo = new PageInfo();
		context.addDataList("abiList", this.getTableModelDAO().queryList(sql,
				abiPageInfo, new Object[] { appId }));
		context.addPageInfo("abiList", abiPageInfo);

		// 查询交易日志数据并放入到上下文中
		sql = "select * from app_trade_log where app_id=? order by trade_serial_no desc";
		PageInfo pageInfo = new PageInfo();
		context.addDataList("atlList", this.getTableModelDAO().queryList(sql,
				pageInfo, new Object[] { appId }));
		context.addPageInfo("atlList", pageInfo);

		// 将数据上下文放到属性中
		request.setAttribute("context", super.context);
		return "monitor/monitor";
	}

	/**
	 * 监控(通讯前置)
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "communication")
	public String communication(HttpServletRequest request) throws Exception {

		// 取得传入应用标识
		String appId = request.getParameter("appid");
		String appName = java.net.URLDecoder.decode(request
				.getParameter("appName"), "UTF-8");
		if (StringUtils.isEmpty(appId)) {
			throw new Exception("必须传入应用标识(appid)参数!");
		}

		// 查询应用基本数据并放入到上下文中
		String sql = "select * from app_frame_comm where app_id=?";
		PageInfo pageInfo = new PageInfo();
		context.addDataList("afcList", this.getTableModelDAO().queryList(sql,
				pageInfo, new Object[] { appId }));
		context.addPageInfo("afcList", pageInfo);

		// 将数据上下文放到属性中
		request.setAttribute("context", super.context);
		request.setAttribute("appName", appName);

		return "monitor/communication";
	}

	/**
	 * 监控(资源使用)
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "resources")
	public String resources(HttpServletRequest request) throws Exception {
		return "monitor/resources";
	}
	
	/**
	 * 用户地区分布
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "appUserAreaAnalysis")
	public String appUserAreaAnalysis(HttpServletRequest request) throws Exception {
		String appId = request.getParameter("appid");
		List<AppDeviceRegister> list = appDeviceRegisterService.queryWithByProvince(appId);
		System.out.println("用户数据：list.size-->"+list.size());
		int maxCount = 1000;
		String detail = "";
		List<String> content = new ArrayList<String>();
		if(list != null && list.size() > 0){
			String str = "";
			maxCount = list.get(0).getAmount();
			System.out.println("用户数量最大值：maxCount-->"+maxCount);
			for(int i=0;i<list.size();i++){
				AppDeviceRegister adr = list.get(i);
				if(i < 10){
					if("".equals(detail)){
						detail = adr.getProvinceName() + "：" + adr.getAmount();
					}else{
						detail += "，" + adr.getProvinceName() + "：" + adr.getAmount();
					}
				}
				str = "{name:'"+adr.getProvinceName()+"',value:"+adr.getAmount()+"}";
				content.add(str);
			}
		}else{
			detail = "没有相关数据";
		}
		System.out.println("content====="+JSON.toJSONString(content).replaceAll("\"", ""));
		request.setAttribute("appid", appId);
		request.setAttribute("maxCount", maxCount);
		request.setAttribute("detail", detail);
		request.setAttribute("content", JSON.toJSONString(content).replaceAll("\"", ""));
		return "monitor/appUserAreaAnalysis";
	}
	
	/**
	 * APP功能分析
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "appTradeUsedAnalysis")
	public String appTradeUsedAnalysis(HttpServletRequest request) throws Exception {
		String appId = request.getParameter("appid");
		String flag = request.getParameter("flag"); //1-APP功能使用分析     2-APP日交易量分析
		String detail = "";
		List<String> content = new ArrayList<String>();
		String array = "";
		if("1".equals(flag)){
			System.out.println("进入APP功能使用分析...");
			int sum = appDeviceRegisterService.querySumWithBytradeCode(appId);
			System.out.println("sum="+sum);
			//适用于MYSQL
			List<AppTradeLog> list = appDeviceRegisterService.queryWithBytradeCode(appId);
			//适用于ORACLE
			//List<AppTradeLog> list = appDeviceRegisterService.queryWithBytradeCodeOracl(appId);
			System.out.println("功能相关数据：list--->"+list);
			if(list != null && list.size() > 0){
				String str = "";
				int count = 0;
				for(AppTradeLog log : list){
					count += log.getAmount();
					if("".equals(detail)){
						detail = log.getTradeName() + "：" + log.getAmount();
					}else{
						detail += "，" + log.getTradeName() + "：" + log.getAmount();
					}
					if("".equals(array)){
						array = "'" + log.getTradeName() + "'";
					}else{
						array += ",'" + log.getTradeName() + "'";
					}
					str = "{value:"+log.getAmount()+",name:'"+log.getTradeName()+"'}";
					content.add(str);
				}
				detail += "，其他：" + (sum-count);
				//其他比例
				array += ",'其他'";
				content.add("{value:"+(sum-count)+",name:'其他'}");
				System.out.println("array="+array+"--综合="+count+",其他=="+(sum-count)+"--content="+JSON.toJSONString(content).replaceAll("\"", "")+"--detail="+detail);
				request.setAttribute("content", JSON.toJSONString(content).replaceAll("\"", ""));
			}else{
				System.out.println("没有相关数据");
				detail = "没有相关数据";
				array = "null";
				content.add("{value:0,name:'null'}");
				request.setAttribute("content", JSON.toJSONString(content).replaceAll("\"", ""));
			}
			request.setAttribute("appid", appId);
			request.setAttribute("detail", detail);
			request.setAttribute("array", array);
			return  "monitor/appTradeUsedAnalysis";
		}else{
			System.out.println("进入APP日交易量分析...");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//格式化对象
			Calendar calendar = Calendar.getInstance();//日历对象
			calendar.setTime(new Date());//设置当前日期
			calendar.add(Calendar.MONTH, -1);//月份减一
			String res = sdf.format(calendar.getTime());
			//适用于MYSQL
			List<AppTradeLog> list = appDeviceRegisterService.queryWithByStartTime(appId, res);
			//适用于ORACLE
			//List<AppTradeLog> list = appDeviceRegisterService.queryWithByStartTimeOracl(appId, res);
			System.out.println("日交易量list=="+list);
			int maxCount = 1000;
			StringBuilder dates = new StringBuilder("");
			StringBuilder numbers = new StringBuilder("");
			if(list != null && list.size() > 0){
				//适用于MYSQL
				maxCount = appDeviceRegisterService.querySumWithByStartTime(appId, res);
				//适用于ORACLE
				//maxCount = appDeviceRegisterService.querySumWithByStartTimeOracl(appId, res);
				System.out.println("maxCount=="+maxCount);
				for(int i=0;i<list.size();i++){
					AppTradeLog atl = list.get(i);
					if("".equals(detail)){
						detail = atl.getStartTime() + "访问量：" + atl.getAmount();
					}else{
						detail += "，" + atl.getStartTime() + "：" + atl.getAmount();
					}
					if(dates.length() == 0){
						dates.append("'"+getFormDate(atl.getStartTime())+"'");
					}else{
						dates.append(",'"+getFormDate(atl.getStartTime())+"'");
					}
					if(numbers.length() == 0){
						numbers.append(atl.getAmount());
					}else{
						numbers.append(","+atl.getAmount());
					}
				}
				System.out.println("dates="+dates+",numbers="+numbers+",detail="+detail+",maxCount="+maxCount);
			}else{
				System.out.println("APP日交易量没有相关数据:list.size="+list.size());
				detail = "没有相关数据";
			}
			request.setAttribute("appid", appId);
			request.setAttribute("dates", dates);
			request.setAttribute("detail", detail);
			request.setAttribute("numbers", numbers);
			request.setAttribute("maxCount", maxCount);
			return "monitor/tradeDateAmountAnalysis";
		}
	}
	
	public String getFormDate(String date){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		String res = "";
		try {
			res = new SimpleDateFormat("yyyy/MM/dd").format(sdf.parse(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return res;
	}
	
	/**
	 * 手机系统安装比例分析
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "appModelTypeAnalysis")
	public String appModelTypeAnalysis(HttpServletRequest request) throws Exception {
		String appId = request.getParameter("appid");
		String flag = request.getParameter("flag"); //1-手机系统安装比例     2-手机型号安装比例
		String detail = "";
		List<String> content = new ArrayList<String>();
		String array = "";
		if("1".equals(flag)){
			System.out.println("进入手机系统安装比例 分析...");
			int sum = appDeviceRegisterService.querySumWithByDeviceType(appId);
			System.out.println("sum="+sum);
			List<AppDeviceRegister> list = appDeviceRegisterService.queryWithByDeviceType(appId);
			if(list != null && list.size() > 0){
				String str = "";
				int count = 0;
				for(AppDeviceRegister app : list){
					count += app.getAmount();
					if("".equals(detail)){
						detail = app.getDeviceType() + "：" + app.getAmount();
					}else{
						detail += "，" + app.getDeviceType() + "：" + app.getAmount();
					}
					if("".equals(array)){
						array = "'" + app.getDeviceType() + "'";
					}else{
						array += ",'" + app.getDeviceType() + "'";
					}
					str = "{value:"+app.getAmount()+",name:'"+app.getDeviceType()+"'}";
					content.add(str);
				}
				detail += "，其他：" + (sum-count);
				//其他比例
				array += ",'其他'";
				content.add("{value:"+(sum-count)+",name:'其他'}");
				System.out.println("array="+array+"--综合="+count+",其他=="+(sum-count)+"--content="+JSON.toJSONString(content).replaceAll("\"", "")+"--detail="+detail);
				request.setAttribute("content", JSON.toJSONString(content).replaceAll("\"", ""));
			}else{
				System.out.println("没有相关数据");
				detail = "没有相关数据";
				array = "null";
				content.add("{value:0,name:'null'}");
				request.setAttribute("content", JSON.toJSONString(content).replaceAll("\"", ""));
			}
			request.setAttribute("appid", appId);
			request.setAttribute("detail", detail);
			request.setAttribute("array", array);
			return  "monitor/appDeviceTypeAnalysis";
		}else{
			System.out.println("进入手机型号安装比例分析...");
			int sum = appDeviceRegisterService.querySumWithByDeviceModel(appId);
			System.out.println("sum="+sum);
			List<AppDeviceRegister> list = appDeviceRegisterService.queryWithByDeviceModel(appId);
			if(list != null && list.size() > 0){
				String str = "";
				int count = 0;
				for(AppDeviceRegister app : list){
					count += app.getAmount();
					if("".equals(detail)){
						detail = app.getDeviceModel() + "：" + app.getAmount();
					}else{
						detail += "，" + app.getDeviceModel() + "：" + app.getAmount();
					}
					if("".equals(array)){
						array = "'" + app.getDeviceModel() + "'";
					}else{
						array += ",'" + app.getDeviceModel() + "'";
					}
					str = "{value:"+app.getAmount()+",name:'"+app.getDeviceModel()+"'}";
					content.add(str);
				}
				detail += "，其他：" + (sum-count);
				//其他比例
				array += ",'其他'";
				content.add("{value:"+(sum-count)+",name:'其他'}");
				System.out.println("array="+array+"--综合="+count+",其他=="+(sum-count)+"--content="+JSON.toJSONString(content).replaceAll("\"", "")+"--detail="+detail);
				request.setAttribute("content", JSON.toJSONString(content).replaceAll("\"", ""));
			}else{
				System.out.println("没有相关数据");
				detail = "没有相关数据";
				array = "null";
				content.add("{value:0,name:'null'}");
				request.setAttribute("content", JSON.toJSONString(content).replaceAll("\"", ""));
			}
			request.setAttribute("appid", appId);
			request.setAttribute("detail", detail);
			request.setAttribute("array", array);
			return "monitor/appDeviceModelAnalysis";
		}
	}

}